﻿var SponsorProtocolSelectorVm = function() {
    var self = this;
    BaseVm.call(self);

    self.IsInitialized = ko.observable(false);
    self.Sponsors = ko.observableArray([]);
    self.Protocols = ko.observableArray([]);
    self.SelectedSponsor = ko.observable();
    self.SelectedProtocol = ko.observable();

    self.Show = ko.observable(false);
    self.Deferrer = null;

    self.Save = function() {
        if (self.SelectedSponsor() == null) {
            alert("You must select a sponsor.");
            return;
        }
        if (self.SelectedProtocol() == null) {
            alert("You must select a protocol.");
            return;
        }
        self.Deferrer.resolve(self.SelectedSponsor(), self.SelectedProtocol());
        self.Close();
    };

    self.Cancel = function() {
        self.Deferrer.reject();
        self.Close();
        self.Deferrer = null;
    };

    self.Close = function() {
        self.Show(false);
        $.colorbox.close();
    };
    self.PromptUserForSponsorAndProtocol = function (jsonData) {
        self.Sponsors.removeAll();
        var parsedJson = JSON.parse(jsonData);
        for (var i = 0; i < parsedJson.length; i++) {
            self.Sponsors.push(parsedJson[i]);
        }

        self.Deferrer = $.Deferred();
        self.Show(true);
        self.ShowColorBox();
        return self.Deferrer;
    };

    self.ShowColorBox = function() {
        var height = $("#SponsorProtocolSelector").height();
        var colorBoxOptions = {
            href: "#SponsorProtocolSelector",
            inline: true,
            height: height,
            innerWidth: 300,
            minHeight: 100,
            maxHeight: $(window).height(),
            overlayClose: false,
            escKey: false,
            transition: "fade"
        };
        $.colorbox(colorBoxOptions);
    };

    self.SelectedSponsor.subscribe(function (selectedSponsor) {
        if (selectedSponsor == null || self.Sponsors() == null)
            return;

        self.Protocols.removeAll();

        self.GetData("/Studies/GetProtocolsBySponsor", selectedSponsor)
            .done(function(data) {
                var parsedJson = JSON.parse(data);
                for (var i = 0; i < parsedJson.length; i++) {
                    self.Protocols.push(parsedJson[i]);
                }
                self.IsInitialized(true);
            });
    });

    $(document).bind('cbox_complete', function() {
        $.colorbox.resize();
    });
};